﻿using Azure.Identity;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Xmu.Stores.Models;
using XmuAuthen.Services;
using XmuAuthor.Models;
using XmuAuthor.Services;

namespace UserStores.Controllers
{
    [ApiController]
    [Route("/api/user/{action}")]
    public class UserApiController : Controller
    {
        private IUserStore userStore;
        private AuthenService authenService;
        private AuthorizationService authorizationService;

        public UserApiController(IUserStore userStore, AuthenService authenService, AuthorizationService authorizationService) 
        {
            this.userStore = userStore;
            this.authenService = authenService;
            this.authorizationService = authorizationService;
        }

        public ActionResult AddUser([FromBody] User user)
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "addUser"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            var (success, msg) = userStore.AddUser(user);
            // 这里userReturn 是 IUserPrincipal 类型，不会显示电话 邮箱等属性，但是存储在AllUsers中的是User类型，会显示电话 邮箱等属性
            return Ok(new
            {
                success,
                msg
            });
        }

        [HttpDelete]
        public ActionResult RemoveUser()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "removeUser"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            string UserName = Request.Query[nameof(UserName)].ToString();           
            var (result, msg) = userStore.RemoveUser(UserName);
            return Ok(new
            {
                success = result,
                msg = msg
            });
        }

        // 获取所有用户
        // 需要验证
        public ActionResult GetAllUsers()
        {
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "getAllUsers"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            int pageSize = 10;
            int pageIndex = 1;
            try
            {
                pageSize = int.Parse(Request.Query[nameof(pageSize)].ToString());
                pageIndex = int.Parse(Request.Query[nameof(pageIndex)].ToString());
            }
            catch
            {
                Console.WriteLine("****** GetAllUsers：使用默认值 ********");
            }

            var (res, users, msg,pageNum) = userStore.GetUserList(pageSize,pageIndex-1);

            return Ok(new
            {
                success = res,
                msg = msg,
                userList = users,
                pageNum=pageNum
            });
        }

        // 已停用：
        public ActionResult GetPageNum()
        {
            string PageSize = Request.Query[nameof(PageSize)].ToString();
            // 获取Credential并验证
            string _accessToken_ = Request.Headers[nameof(_accessToken_)].ToString();
            Guid? userId = authenService.GetUserId(_accessToken_);
            if (userId == null)
            {
                return Json(new
                {
                    success = false,
                    msg = "accessToken无效"
                });
            }

            // 查看Credential对应的用户是否具有该Resource
            if (!authorizationService.checkResource((Guid)userId, "getPageNum"))
            {
                return Json(new
                {
                    success = false,
                    msg = "用户无权限"
                });
            }

            int pageSize = int.Parse(PageSize);
            var pageNum = userStore.GetPageNum(pageSize);
            return Ok(new
            {
                success = true,
                msg = "成功获取页数",
                pageNums = pageNum
            });
        }

        private bool VerifyToken(string _accessToken_)
        {
            IUserPrincipal? user = authenService.Check(_accessToken_);
            // 用户token验证
            if (user == null)
            {
                return false;
            }
            return true;
        }

        
    }
}
